//
//  LYCalendarPicker.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/30.
//

import UIKit
import SnapKit

protocol LYCalendarPickerDelegate: AnyObject {
    func calendarPicker(_ picker: LYCalendarPicker, didSelectDate date: Date)
}

class LYCalendarPicker: UIView {
    
    // MARK: - 属性
    weak var delegate: LYCalendarPickerDelegate?
    private var selectedDate: Date
    
    // MARK: - UI 组件
    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemBackground
        view.layer.cornerRadius = 12
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.1
        view.layer.shadowOffset = CGSize(width: 0, height: 2)
        view.layer.shadowRadius = 10
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = LYlocalizedString("Date Selection")
        label.font = .systemFont(ofSize: 18, weight: .medium)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var columnsContainer: UIView = {
        let view = UIView()
        return view
    }()
    
    // 列标题 (顺序改为日、月、年)
    private lazy var dayTitleLabel: UILabel = {
        let label = UILabel()
        label.text = LYlocalizedString("Day")
        label.font = .systemFont(ofSize: 14, weight: .semibold)
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#000000")
        return label
    }()
    
    private lazy var monthTitleLabel: UILabel = {
        let label = UILabel()
        label.text = LYlocalizedString("Month")
        label.font = .systemFont(ofSize: 14, weight: .semibold)
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#000000")
        return label
    }()
    
    private lazy var yearTitleLabel: UILabel = {
        let label = UILabel()
        label.text = LYlocalizedString("Year")
        label.font = .systemFont(ofSize: 14, weight: .semibold)
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#000000")
        return label
    }()
    
    // 列内容 (顺序改为日、月、年)
    private lazy var dayColumn: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(LYCalendarDayCell.self, forCellWithReuseIdentifier: "LYCalendarDayCell")
        collectionView.showsVerticalScrollIndicator = false
        collectionView.tag = 2
        return collectionView
    }()
    
    private lazy var monthColumn: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(LYCalendarMonthCell.self, forCellWithReuseIdentifier: "LYCalendarMonthCell")
        collectionView.showsVerticalScrollIndicator = false
        collectionView.tag = 1
        return collectionView
    }()
    
    private lazy var yearColumn: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(LYCalendarYearCell.self, forCellWithReuseIdentifier: "LYCalendarYearCell")
        collectionView.showsVerticalScrollIndicator = false
        collectionView.tag = 0
        return collectionView
    }()
    
    private lazy var confirmButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(LYlocalizedString("Confirm"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = .systemBlue
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 22
        button.addTarget(self, action: #selector(confirmSelection), for: .touchUpInside)
        return button
    }()
    
    private lazy var separator1: UIView = {
        let view = UIView()
        view.backgroundColor = .systemGray5
        return view
    }()
    
    private lazy var separator2: UIView = {
        let view = UIView()
        view.backgroundColor = .systemGray5
        return view
    }()
    
    // MARK: - 数据
    private var years: [Int] = []
    private var months: [Int] = Array(1...12)
    private var days: [Int] = []
    
    private var selectedYear: Int = 0
    private var selectedMonth: Int = 0
    private var selectedDay: Int = 0
    
    // MARK: - 初始化
    init(selectedDate: Date = Date()) {
        self.selectedDate = selectedDate
        super.init(frame: .zero)
        
        setupData()
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 数据准备
    private func setupData() {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day], from: selectedDate)
        
        selectedYear = components.year ?? 1990
        selectedMonth = components.month ?? 1
        selectedDay = components.day ?? 1
        
        // 生成年份范围 (当前年份前后20年)
        let currentYear = calendar.component(.year, from: Date())
        years = Array((currentYear-120)...(currentYear))
        
        // 生成当月天数
        updateDays()
    }
    
    private func updateDays() {
        let calendar = Calendar.current
        let dateComponents = DateComponents(year: selectedYear, month: selectedMonth)
        if let date = calendar.date(from: dateComponents),
           let range = calendar.range(of: .day, in: .month, for: date) {
            days = Array(range.lowerBound..<range.upperBound)
        } else {
            days = Array(1...31)
        }
        
        // 确保选中的日期有效
        if selectedDay > days.count {
            selectedDay = days.count
        }
        dayColumn.reloadData()
    }
    
    // MARK: - UI 设置 (使用 SnapKit)
    private func setupUI() {
        addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(columnsContainer)
        containerView.addSubview(confirmButton)
        
        // 添加列标题 (日、月、年顺序)
        columnsContainer.addSubview(dayTitleLabel)
        columnsContainer.addSubview(monthTitleLabel)
        columnsContainer.addSubview(yearTitleLabel)
        
        // 添加列内容 (日、月、年顺序)
        columnsContainer.addSubview(dayColumn)
        columnsContainer.addSubview(separator1)
        columnsContainer.addSubview(monthColumn)
        columnsContainer.addSubview(separator2)
        columnsContainer.addSubview(yearColumn)
        
        // 容器视图约束
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 标题约束
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        // 列容器约束
        columnsContainer.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(350)
        }
        
        // 列标题约束 (日、月、年顺序)
        dayTitleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.3)
            make.height.equalTo(30)
        }
        
        monthTitleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalTo(dayTitleLabel.snp.trailing)
            make.width.equalToSuperview().multipliedBy(0.3)
            make.height.equalTo(30)
        }
        
        yearTitleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.trailing.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.3)
            make.height.equalTo(30)
        }
        
        // 日期列约束 (最左侧)
        dayColumn.snp.makeConstraints { make in
            make.top.equalTo(dayTitleLabel.snp.bottom).offset(10)
            make.bottom.leading.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.3)
        }
        
        // 分隔线1
        separator1.snp.makeConstraints { make in
            make.top.equalTo(dayTitleLabel.snp.bottom).offset(10)
            make.bottom.equalToSuperview()
            make.leading.equalTo(dayColumn.snp.trailing)
            make.width.equalTo(1)
        }
        
        // 月份列约束 (中间)
        monthColumn.snp.makeConstraints { make in
            make.top.equalTo(monthTitleLabel.snp.bottom).offset(10)
            make.bottom.equalToSuperview()
            make.leading.equalTo(separator1.snp.trailing)
            make.width.equalToSuperview().multipliedBy(0.3)
        }
        
        // 分隔线2
        separator2.snp.makeConstraints { make in
            make.top.equalTo(yearTitleLabel.snp.bottom).offset(10)
            make.bottom.equalToSuperview()
            make.leading.equalTo(monthColumn.snp.trailing)
            make.width.equalTo(1)
        }
        
        // 年份列约束 (最右侧)
        yearColumn.snp.makeConstraints { make in
            make.top.equalTo(yearTitleLabel.snp.bottom).offset(10)
            make.bottom.trailing.equalToSuperview()
            make.leading.equalTo(separator2.snp.trailing)
        }
        
        // 确定按钮约束
        confirmButton.snp.makeConstraints { make in
            make.top.equalTo(columnsContainer.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        // 初始滚动到选中位置
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.scrollToSelectedPositions(animated: false)
        }
    }
    
    private func scrollToSelectedPositions(animated: Bool) {
        if let dayIndex = days.firstIndex(of: selectedDay) {
            dayColumn.scrollToItem(
                at: IndexPath(item: dayIndex, section: 0),
                at: .centeredVertically,
                animated: animated
            )
        }
        
        monthColumn.scrollToItem(
            at: IndexPath(item: selectedMonth - 1, section: 0),
            at: .centeredVertically,
            animated: animated
        )
        
        if let yearIndex = years.firstIndex(of: selectedYear) {
            yearColumn.scrollToItem(
                at: IndexPath(item: yearIndex, section: 0),
                at: .centeredVertically,
                animated: animated
            )
        }
    }
    
    // MARK: - 操作
    @objc private func confirmSelection() {
        let calendar = Calendar.current
        if let date = calendar.date(from: DateComponents(year: selectedYear, month: selectedMonth, day: selectedDay)) {
            selectedDate = date
            delegate?.calendarPicker(self, didSelectDate: date)
        }
    }
}

// MARK: - CollectionView 数据源和代理
extension LYCalendarPicker: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView.tag {
        case 0: return years.count       // 年
        case 1: return months.count      // 月
        case 2: return days.count        // 日
        default: return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch collectionView.tag {
        case 0: // 年
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYCalendarYearCell", for: indexPath) as! LYCalendarYearCell
            let year = years[indexPath.item]
            cell.configure(year: year, isSelected: year == selectedYear)
            return cell
            
        case 1: // 月
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYCalendarMonthCell", for: indexPath) as! LYCalendarMonthCell
            let month = months[indexPath.item]
            cell.configure(month: month, isSelected: month == selectedMonth)
            return cell
            
        case 2: // 日
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYCalendarDayCell", for: indexPath) as! LYCalendarDayCell
            let day = days[indexPath.item]
            cell.configure(day: day, isSelected: day == selectedDay)
            return cell
            
        default:
            fatalError("Unknown collection view")
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 30)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch collectionView.tag {
        case 0: // 年
            selectedYear = years[indexPath.item]
            updateDays()
            
        case 1: // 月
            selectedMonth = months[indexPath.item]
            updateDays()
            
        case 2: // 日
            selectedDay = days[indexPath.item]
            
        default:
            break
        }
        
        collectionView.reloadData()
    }
}

// MARK: - 自定义单元格
class LYCalendarYearCell: UICollectionViewCell {
    private let yearLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 16)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(yearLabel)
        
        yearLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(year: Int, isSelected: Bool) {
        yearLabel.text = "\(year)"
        yearLabel.textColor = isSelected ? UIColor(hex: "#000000") : UIColor(hex: "#999999")
        contentView.backgroundColor = isSelected ? UIColor(hex: "#FFEEC5") : .clear
        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = 15.0
    }
}

class LYCalendarMonthCell: UICollectionViewCell {
    private let monthLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 16)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(monthLabel)
        
        monthLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(month: Int, isSelected: Bool) {
        monthLabel.text = "\(month)"
        monthLabel.textColor = isSelected ? UIColor(hex: "#000000") : UIColor(hex: "#999999")
        contentView.backgroundColor = isSelected ? UIColor(hex: "#FFEEC5") : .clear
        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = 15.0
    }
}

class LYCalendarDayCell: UICollectionViewCell {
    private let dayLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 16)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(dayLabel)
        
        dayLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(day: Int, isSelected: Bool) {
        dayLabel.text = "\(day)"
        dayLabel.textColor = isSelected ? UIColor(hex: "#000000") : UIColor(hex: "#999999")
        contentView.backgroundColor = isSelected ? UIColor(hex: "#FFEEC5") : .clear
        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = 15.0
    }
}
